import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import {setToken, getToken, canTurnTo, setTitle, getMenuByRouter} from '@/libs/util'
import config from '@/config'
import routers from "@/router/routers";
import {connect} from "@/api/im";
const { homeName } = config
import {getUserInfo} from "@/api/auth";
//NProgress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
//VueRouter
Vue.use(Router)
const router = new Router({
  base:'/',
  routes,
  mode: 'hash'
})

const LOGIN_PAGE_NAME = 'signin'

const SIGNUP_PAGE_NAME = 'signup'

const FORGOT_PWD_PAGE_NAME = 'forgot'

const WELCOME_PAGE_NAME = 'welcome'

const originalPush = Router.prototype.push

Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

async function getUser(){
  if(store.state.userInfo != null) {
    return store.state.userInfo
  }
  let token = getToken()
  if(token) {
    let userInfo = null
    await getUserInfo().then(user => {
      if(user.code == 200) {
        store.commit('updateUserInfo',user.data)
        if(user.tenantId != null) {
          connect()
        }
      }
      userInfo =  user.code == 200 ? user.data : null;
    })
    return userInfo
  }
  return null
}

router.beforeEach((to, from, next) => {
  NProgress.start();
  if(to.name === SIGNUP_PAGE_NAME || to.name === FORGOT_PWD_PAGE_NAME || to.name === LOGIN_PAGE_NAME) {
    next()
    return
  }
  getUser().then(user => {
    //未登录，前往登录页
    if (!user && to.name !== LOGIN_PAGE_NAME) {
      next({
        replace:true,
        path: '/signin?target=' + to.path
      })
      return
    }
    //用户未创建或加入企业，前往企业引导页面
    if(user.tenantId == null || user.tenantId == '') {
      //当前页面为企业引导页面，放行
      if(to.name === WELCOME_PAGE_NAME) {
        next()
        return
      }
      //强制前往企业引导页面
      next({
        replace:true,
        path: '/welcome'
      })
      return
    }else if(to.name === WELCOME_PAGE_NAME){
      //已加入tenant,返回首页
      next({
        replace:true,
        path: '/'
      })
      return
    }
    //已登录，获取用户可以看到的导航菜单
    let menus = getMenuByRouter(routers, user.access,to.path)
    store.commit('updateMenuList',menus)
    next()
  }).catch(() => {
    next({
      replace:true,
      path: '/signin?target=' + to.path
    })
  })
})

router.afterEach(to => {
  setTitle(to, router.app)
  window.scrollTo(0, 0)
  NProgress.done()
})

export default router
